package cn.winwintech.screenlocker

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat

/**
 * Foreground service maintaining persistent execution for scheduled screen locks
 */
class LockScreenService : Service() {
    // Notification identifiers for foreground service
    private val NOTIFICATION_ID = 1  // Unique ID for persistent notification
    private val CHANNEL_ID = "keep_alive_channel"  // Channel ID for Android 8.0+

    /**
     * Service initialization - creates notification channel and starts foreground service
     */
    override fun onCreate() {
        super.onCreate()
        // 创建通知渠道（Android 8.0+ 必需）
        createNotificationChannel()
        // 构建通知并启动前台服务
        val notification = buildNotification()
        try {
            startForeground(NOTIFICATION_ID, notification)
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        }
    }

    /**
     * Configure service restart behavior
     * @return START_STICKY to auto-restart service if terminated
     */
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY // 服务被终止后自动重启
    }

    /**
     * Create notification channel required for Android Oreo+ foreground services
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Keep Alive Channel",
                NotificationManager.IMPORTANCE_HIGH
            ).apply { description = "Channel for background service" }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager?.createNotificationChannel(channel)
        }
    }

    /**
     * Build persistent notification for foreground service
     * @return Notification showing background operation status
     */
    private fun buildNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("应用运行中")
            .setContentText("正在保持后台任务执行")
            .setSmallIcon(R.drawable.logo)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()
    }

    override fun onBind(intent: Intent?): IBinder? = null
}
